package com.goalias.filter;

import com.goalias.config.RequestUriKeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class DDosFilter {//令牌桶限流

    @Resource
    private RequestUriKeyResolver requestUriKeyResolver;

    @Bean
    public RouteLocator abilityRateLimitRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/ability/**")
                        .filters(f -> f.requestRateLimiter()
                                .rateLimiter(RedisRateLimiter.class, c -> c.setBurstCapacity(10).setReplenishRate(1).setRequestedTokens(1))
                                .configure(c -> c.setKeyResolver(requestUriKeyResolver)))
                                .uri("lb://ability-expansion"))
                        .build();
    }
    @Bean
    public RouteLocator userRateLimitRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/user/**")
                        .filters(f -> f.requestRateLimiter()
                                .rateLimiter(RedisRateLimiter.class, c -> c.setBurstCapacity(10).setReplenishRate(1).setRequestedTokens(1))
                                .configure(c -> c.setKeyResolver(requestUriKeyResolver)))
                                .uri("lb://user-manager"))
                        .build();
    }
    @Bean
    public RouteLocator contentRateLimitRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/content/**")
                        .filters(f -> f.requestRateLimiter()
                                .rateLimiter(RedisRateLimiter.class, c -> c.setBurstCapacity(20).setReplenishRate(1).setRequestedTokens(1))
                                .configure(c -> c.setKeyResolver(requestUriKeyResolver)))
                                .uri("lb://content-integration"))
                        .build();
    }
}
